using AutoMapper;
using BaseData.CommonLib.Models;
using BaseData.DomainLib.AggregatesModel.MaterialCategoryAggregate;
using MediatR;
using Swimj.CommonLib.Base;

namespace BaseData.ApplicationLib.Commands
{
    public class UpdateMaterialCategoryCommand : MaterialCategoryEditRequestDto,
        IRequest<Result<MaterialCategoryInfoResponseDto>>
    {
        public int Id { get; set; }
    }

    public class UpdateMaterialCategoryCommandHandler : IRequestHandler<UpdateMaterialCategoryCommand, Result<MaterialCategoryInfoResponseDto>>
    {

        private readonly IMaterialCategoryRepository _materialCategoryRepository;
        private readonly IMapper _mapper;

        public UpdateMaterialCategoryCommandHandler(IMaterialCategoryRepository materialCategoryRepository,
        IMapper mapper)
        {
            _materialCategoryRepository = materialCategoryRepository;
            _mapper = mapper;
        }

        public async Task<Result<MaterialCategoryInfoResponseDto>> Handle(UpdateMaterialCategoryCommand request, CancellationToken cancellationToken)
        {
            var materialCategory = await _materialCategoryRepository.Get(request.Id);
            materialCategory?.Update(request.Name, request.ParentId, request.Sort, request.Description);

            await _materialCategoryRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

            return await Result<MaterialCategoryInfoResponseDto>.SuccessAsync(_mapper.Map<MaterialCategoryInfoResponseDto>(materialCategory));
        }
    }
}